package com.xzc.algorithm.data_structure_ke.ArrayList.array;

import lombok.Data;

@Data
public class _1_Array<E> {
    private E[] data;
    private int size;

    public _1_Array() {
        this(10);
    }

    public _1_Array(int capability) {
        data = (E[]) new Object[capability];
        size = 0;
    }

    public int getSize() {
        return size;
    }

    public int getCapability() {
        return data.length;
    }

    public E getLast() {
        return get(size - 1);
    }

    public E getFirst() {
        return get(0);
    }

    public E get(int index) {
        if (index < 0 || index > size - 1) {
            throw new IllegalArgumentException("索引必须大于等于0，小于等于size-1");
        }
        return data[index];
    }

    public void addFirst(E e) {
        add(0, e);
    }

    public void addLast(E e) {
        add(size, e);
    }

    public void add(int index, E e) {
        if (index < 0 || index > size) {
            throw new IllegalArgumentException("索引必须大于等于0，小于等于size");
        }
        if (size == data.length) {
            resize(data.length * 2);
        }
        for (int i = size - 1; i >= index; i--) {
            data[i + 1] = data[i];
        }
        data[index] = e;
        size++;
    }

    public E removeFirst() {
        return remove(0);
    }

    public E removeLast() {
        return remove(size - 1);
    }

    public E remove(int index) {
        if (index < 0 || index > size - 1) {
            throw new IllegalArgumentException("索引必须大于等于0，小于等于size-1");
        }
        E res = data[index];
        for (int i = index; i < size; i++) {
            data[i] = data[i + 1];
        }
        size--;
        if (size == data.length / 4) {
            resize(data.length / 2);
        }
        return res;
    }

    private void resize(int capability) {
        if (capability < size)
            throw new IllegalArgumentException("新的容量不能比当前SIZE小");
        E[] tmp = (E[]) new Object[capability];
        for (int i = 0; i < size; i++) {
            tmp[i] = data[i];
        }
        data = tmp;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (E i : data) {
            sb.append(i).append(",");
        }
        sb.append("]");
        sb.append(" size=").append(size).append(" length=").append(data.length);
        return sb.toString();
//        return "";
    }
}
